import { useStore } from 'vuex'
import { computed, ref, watch } from 'vue'
import { getLyric } from '@/service/song'
import Lyric from 'lyric-parser/src'

export default function useLyric ({ songReady, currentTime }) {
  const store = useStore()
  // Lyric对象实例
  const currentLyric = ref(null)
  const lyricListRef = ref(null)
  const lyricScrollRef = ref(null)
  const playingLyric = ref('')

  // 歌词行号
  const currentLineNum = ref(0)
  const currentSong = computed(() => store.getters.currentSong)

  watch(currentSong, async (newSong) => {
    // 切换歌曲，暂停歌词
    currentLyric.value = null
    currentLineNum.value = 0
    playingLyric.value = ''

    const { lyric } = await getLyric(newSong)
    store.commit('addSongLyric', {
      song: newSong,
      lyric
    })
    // 获取歌词时，点击切歌，歌曲发生变化
    // getLyric请求回来，此时已经是下一首，没必要再解析上一首歌了
    if (!lyric) return
    if (newSong.lyric === lyric) {
      currentLyric.value = new Lyric(lyric, handleLyric)
    }
    if (songReady.value) {
      console.log('歌曲已准备好，播放歌词')
      playLyric()
    }
  })
  // 歌词滚动实际是Scroll组件滚动
  const handleLyric = ({ lineNum, txt }) => {
    currentLineNum.value = lineNum
    playingLyric.value = txt
    const scrollComp = lyricScrollRef.value
    const listEl = lyricListRef.value
    if (!listEl) return
    if (lineNum > 5) {
      // 获取目标行元素
      const lineEl = listEl.children[lineNum - 5]
      // 滚动到目标行
      scrollComp.scroll.scrollToElement(lineEl, 1000)
    }
  }
  const playLyric = () => {
    const currentLyricVal = currentLyric.value
    if (currentLyricVal) {
      // currentLyricVal.seek（）将歌词的播放进度跳转到指定时间
      // seek方法以ms为单位
      currentLyricVal.seek(currentTime.value * 1000)
    }
  }
  const stopLyric = () => {
    const currentLyricVal = currentLyric.value
    if (currentLyricVal) {
      currentLyricVal.stop()
    }
  }
  return {
    currentLyric,
    currentLineNum,
    lyricListRef,
    lyricScrollRef,
    playingLyric,
    playLyric,
    stopLyric
  }
}
